package nix.demo7.web.filter;

import java.io.File;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class StaticFilter implements Filter {

	private FilterConfig fConfig;
	
	public void init(FilterConfig fConfig) throws ServletException {
		this.fConfig = fConfig;
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {

		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response;
		
		String category = request.getParameter("category");
		String htmlPage = category + ".html";
		String htmlPath = this.fConfig.getServletContext().getRealPath("/demo7/htmls");
		File htmlDir = new File(htmlPath);
		htmlDir.mkdirs();
		File destFile = new File(htmlPath, htmlPage);
		
		if (destFile.exists()) {
			res.sendRedirect(req.getContextPath() + "/demo7/htmls/" + htmlPage);
			return;
		}
		
		// 使用修改后的Response放行，输出至html文件
		StaticResponse sr = new StaticResponse(res, destFile.getAbsolutePath());
		chain.doFilter(request, sr);
		
		res.sendRedirect(req.getContextPath() + "/demo7/htmls/" + htmlPage);
	}

	public void destroy() {

	}

}
